
import React, { Component } from 'react';
import '../styles/Register.scss'
import { user_register } from '../api/index'

import { NavBar, Skeleton, Swiper, Toast } from 'antd-mobile';

class Register extends Component {
    constructor(props) {
        super(props);
        this.state = { phone: '', pass: '', agree: false }
    }
    handleChange(e) {
        this.setState({
            [e.target.name]: e.target.type == 'checkbox' ? e.target.checked : e.target.value
        })
    }
    // 手机号和密码注册验证
    register() {
        if (this.state.phone.trim() != '' && this.state.pass.trim() != '') {
            if (/^1[23456789]\d{9}$/.test(this.state.phone)) {
                // if (/^\S*(?=\S{6,})(?=\S*\d)(?=\S*[A-Z])(?=\S*[a-z])\S*$/.test(this.state.pass)) {
                if (/^[a-z][A-Z]*\d{4,}$/.test(this.state.pass)) {
                    user_register({ phone: this.state.phone, pass: this.state.pass }).then((res) => {
                        console.log(res);
                        // alert('注册成功')
                        Toast.show({
                            icon: 'success',
                            content: '注册成功',
                        })
                        localStorage.setItem('phone', this.state.phone)
                        localStorage.setItem('pass', this.state.pass)
                        this.props.history.push('/login')
                    })
                } else {
                    Toast.show({
                        icon: 'fail',
                        content: '密码格式有误,请按要求输入',
                    })
                }
            } else {
                // alert("手机号格式有误,请核实")
                Toast.show({
                    icon: 'fail',
                    content: '手机号格式有误,请核实',
                })
            }
        } else {
            // alert('请输入手机号')
            Toast.show({
                icon: 'fail',
                content: '请输入手机号',
            })
        }
    }
    render() {
        return (
            <div className='register'>
                <div className="title">注册页</div>
                <div className="block">
                    {/* 对于input textarea select通过value属性和onChange事件让原本非受控的表单元素变为受控元素 */}
                    <input name='phone' value={this.state.phone} onChange={(e) => { this.handleChange(e) }} type="text" placeholder='输入手机号' />
                </div>
                <div className="block">
                    <input name='pass' value={this.state.pass} onChange={(e) => { this.handleChange(e) }} type="text" placeholder='输入密码,例如"aA+(至少4个数字)"' />
                </div>
                <div className="block ">
                    <button onClick={() => { this.register() }}>注册</button>
                    <span onClick={() => { this.props.history.push('/login') }}>已经注册过了?点我去登录</span>
                </div>
            </div>
        );
    }
}

export default Register;